package com.sk.sourcecircle.app;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.StrictMode;
import android.support.multidex.MultiDexApplication;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sk.sourcecircle.common.Constants;
import com.sk.sourcecircle.utils.SPUtils;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;

import org.xutils.x;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by sk on 2017/6/7.
 */

public class MyApplication extends MultiDexApplication {


    private static MyApplication sInstance;
    private ArrayList<AppCompatActivity> activityList;
    private String cookie;
    private IWXAPI iwxapi;
    private Tencent mTencent;
    private IWeiboShareAPI weiboApi;
    public static BaseResp resp = null;
    public int wxPay = 0;
    private String cityId = "159";

    private String cityName = "南昌市";

    private float lng = 115.8581700000f, lat = 28.6826800000f;

    public float getLng() {
        if (lng <= 0) {
            if (SPUtils.contains(this, "lng")) {
                lng = (float) SPUtils.get(this, "lng", 115.8581700000f);
            }
        }
        return lng;
    }

    public void setLng(float lng) {
        this.lng = lng;
        SPUtils.put(getAppContext(), "lng", lng);
    }

    public float getLat() {
        if (lat <= 0 && SPUtils.contains(this, "lat")) {
            lat = (float) SPUtils.get(this, "lat", 28.6826800000f);
            return lat;
        }
        return lat;
    }

    public void setLat(float lat) {
        this.lat = lat;
        SPUtils.put(getAppContext(), "lat", lat);
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
        SPUtils.put(getAppContext(), "cityName", cityName);
    }

    public String getCityId() {
        if (cityId == null || cityId.length() == 0) {
            cityId = (String) SPUtils.get(getAppContext(), "cityId", "159");
        }
        return cityId;
    }

    public void setCityId(String cityId) {
        this.cityId = cityId;
        SPUtils.put(getAppContext(), "cityId", cityId);
    }

    public int getWxPay() {
        return wxPay;
    }

    public void setWxPay(int wxPay) {
        this.wxPay = wxPay;
    }

    public String getCookie() {
        return cookie;
    }

    public void setCookie(String cookie) {
        this.cookie = cookie;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        x.Ext.init(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

//        CrashHandler crashHandler = CrashHandler.getInstance();
//        crashHandler.init(getApplicationContext());

        inLocation();

        initWeixin();
        initTencent();
        initWeibo();

        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
// 如果APP启用了远程的service，此application:onCreate会被调用2次
// 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
// 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回

        if (processAppName == null || !processAppName.equalsIgnoreCase(getAppContext().getPackageName())) {

            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }

        EMOptions options = new EMOptions();


        options.setAutoLogin(true);
// 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
// 是否自动将消息附件上传到环信服务器，默认为True是使用环信服务器上传下载，如果设为 false，需要开发者自己处理附件消息的上传和下载
        options.setAutoTransferMessageAttachments(true);
// 是否自动下载附件类消息的缩略图等，默认为 true 这里和上边这个参数相关联
        options.setAutoDownloadThumbnail(true);
//初始化
        EMClient.getInstance().init(getAppContext(), options);
//在做打包混淆时，关闭debug模式，避免消耗不必要的资源
//        EMClient.getInstance().setDebugMode(true);

//        CrashHandler crashHandler = CrashHandler.getInstance();
//        crashHandler.init(getApplicationContext());
        activityList = new ArrayList<>();
        getAppInfo();
    }

    private void inLocation() {

        if (SPUtils.contains(getAppContext(), "cityId")) {
            cityId = (String) SPUtils.get(getAppContext(), "cityId", "159");
        } else {
            SPUtils.put(getAppContext(), "cityId", "159");
        }

        if (SPUtils.contains(getAppContext(), "lat")) {
            lat = (float) SPUtils.get(getAppContext(), "lat", 115.8581700000f);
        } else {
            SPUtils.put(getAppContext(), "lat", 115.8581700000f);
        }

        if (SPUtils.contains(getAppContext(), "lng")) {
            lng = (float) SPUtils.get(getAppContext(), "lng", 115.8581700000f);
        } else {
            SPUtils.put(getAppContext(), "lng", 28.6826800000f);
        }

        if (SPUtils.contains(getAppContext(), "cityName")) {
            cityName = (String) SPUtils.get(getAppContext(), "cityName", "南昌市");
        } else {
            SPUtils.put(getAppContext(), "cityName", "南昌市");
        }
    }

    /**
     * s
     * 注册微信
     */
    private void initWeixin() {
        iwxapi = WXAPIFactory.createWXAPI(this, Constants.WX_ID);
        iwxapi.registerApp(Constants.WX_ID);
    }

    public IWXAPI getIwxapi() {
        return iwxapi;
    }


    //注册微博
    private void initWeibo() {
        weiboApi = WeiboShareSDK.createWeiboAPI(this, Constants.WEIBO_ID);
        weiboApi.registerApp();
    }

    public IWeiboShareAPI getWeibo() {
        return weiboApi;
    }

    /**
     * 注册QQ
     */
    private void initTencent() {

        mTencent = Tencent.createInstance(Constants.QQ_ID, this.getApplicationContext());
    }

    public Tencent getTencent() {
        return mTencent;
    }


    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();

        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public ArrayList<AppCompatActivity> getActivityList() {
        return activityList;
    }

    /**
     * 获取application 单例
     *
     * @return
     */
    public static MyApplication getInstance() {
        return sInstance;
    }

    /**
     * 获取全局的Context
     * 能用全局尽量用全局，防止内存泄漏
     *
     * @return
     */
    public static Context getAppContext() {
        return sInstance.getApplicationContext();
    }

    public void finishApp() {
        for (AppCompatActivity activity : activityList) {
            activity.finish();
        }
    }

    private String getAppInfo() {
        try {
            String pkName = this.getPackageName();
            String versionName = this.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            int versionCode = this.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            Log.v("getAppInfo", pkName);
            return pkName;
        } catch (Exception e) {
        }
        return null;
    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }
}
